package org.NooLab.glue.msgframe;

import java.text.DecimalFormat;


import org.NooLab.glue.subscription.context.Context;
import org.NooLab.glue.subscription.context.ContextInfra;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.xml.XMessageAbs;

import com.jamesmurty.utils.XMLBuilder;




public class CtxtXMessage extends XMessageAbs{

	
	
	
	public CtxtXMessage( PrintLog outprn ){
		super();
			
		out = outprn;
	}

	/**
	 * 
	 * 
	 * 
	 * @param basics
	 * @param context
	 * @return
	 */
	public String createXmlFromContextForMsgDescsription( BasicMessageParams basics, Context context) {
		String xmlstr="" ;
		 
		XMLBuilder builder ;

		String itemset="", dataitemsStr = "", minimatch, disclosures="", contextName="";
		
		try{
            /*
			
			setContextStyle(ContextInfra._CSTYL_JUSTINFO);
			setDataType( ContextInfra._DTYP_ITEMS );

            */
			DecimalFormat formatter = new DecimalFormat("#.###");
			  
			if (context.getDataType() == 1){
				itemset = strgutil.arr2text( context.getItemSet(), "", ";");
			}
			if (context.getDataType() == 2){
				itemset      = strgutil.arr2text( context.getFeatureSet(), "", ";");
				dataitemsStr = strgutil.arr2text( context.getFeatureValues(), 5, true,  ";");
			}
			
			minimatch = formatter.format( context.getMinimalMatch() );
			
			if (context.getDisclosureAllowData()){
				disclosures = disclosures+"data;";
			}
			if (context.getDisclosureAllowName() ){
				disclosures = disclosures+"name;";
				contextName = context.getNameOfIssuer() ;
				if ((contextName.contentEquals("*")) || (contextName.length()==0)){
					contextName = basics.instanceName ;
				}
			}
			
			
			builder = getXmlBuilder( "context" )
			 								.a("label", context.getLabel() )
			 								.a("style", ""+ context.getContextStyle() ); // e.g. ContextInfra._CSTYL_JUSTINFO 
			
			builder
			        .e("pragma").a("disclosures", disclosures)
			        			.a("datatype", ""+ context.getDataType() ) // e.g. ContextInfra._DTYP_ITEMS
			        	        .a("name", contextName)
			        	        .a("role", basics.roleOfSender )
			             .up()
					.e("items")
					    .e("list").a("values", itemset).up()
					  .up()
					;
			if ( context.getDataType() == ContextInfra._DTYP_FVECTOR ){
				
				builder
					.e("values")
						.e("list").a("values", dataitemsStr).up()
					  .up()
				;
				
			}
			
			
			xmlstr = getXmlStr( builder, false ) ;
			
			xmlstr = xmlstr.replace("\r\n", "$*<>*$      ");
			xmlstr = xmlstr.replace("\n", "$*<>*$      ");
			xmlstr = xmlstr.replace("$*<>*$","\r\n");
			
		}catch(Exception e){
			
		}
		
		
		return xmlstr;
		
	}

	public Context readContextDefinitionForSubscriptionFromXml(String xmlMsg) {
		
		
		return null;
	}
	
	
	/**
	 * converting xml entries into context object;
	 * 
	 * it will return null, if the itemSet can not be found
	 *
	 * @param xmlMsg
	 * @return
	 */
	public Context readContextInfoFromXml(String xmlMsg) {
		
		/*    <transaction>
				<context label="context A">
     				<pragma disclosures="data;name;" name="testSource0" role="SOURCE"/>
     				<items>
        				<list values="x;y;k"/>
     				</items>
  				</context>

		*/
		/* 
		  	context info is quite simple, either it is 
				- a whole-sale format like text or image,
				- an item set, or a 
				- feature vector
		 */ 
		Context  context;
		String 	str,stylestr, labelStr, disclosedPartsStr, issuerName,
				issuerRole, itemsetStr, dataitemStr;
		int dataType, stylev=-1,c=0 ;
		long iid, tid;
		context = new Context();
		String[] itemSet = new String[0];
		String[] datavaluesStr = new String[0];
		double[] featureValues = new double[0];
		
		
		try{
			
			xpathQuery.setXml( xmlMsg ) ;
		
			// xpathQuery
			labelStr = getSpecifiedInfo( xmlMsg,"//context","label") ;
			str = getSpecifiedInfo( xmlMsg,"//transaction/context","label") ;
			stylev = (int)getSpecifiedValue( xmlMsg,"//context","style") ;
			 
			
			c=1;
			if ((stylev == ContextInfra._CSTYL_JUSTINFO) || (c==1)){ // 
				disclosedPartsStr = getSpecifiedInfo( xmlMsg,"//context/pragma","disclosures") ;
				issuerName = getSpecifiedInfo( xmlMsg,"//context/pragma","name") ;
				issuerRole = getSpecifiedInfo( xmlMsg,"//context/pragma","role") ;
	         
				dataType = (int)getSpecifiedValue(xmlMsg,"//context/pragma","datatype") ;
				
				
				context.setLabel(labelStr);
				context.setNameOfIssuer(issuerName);
				context.setRoleOfIssuer(issuerRole);
				if (disclosedPartsStr.toLowerCase().contains("data")){
					context.setDisclosureAllowData(true);
				}
				if (disclosedPartsStr.toLowerCase().contains("name")){
					context.setDisclosureAllowName(true);
				}
				
				context.setDataType(dataType) ;
				
				// C  
				if (dataType == ContextInfra._DTYP_ITEMS){
					
					// <context ...<pragma ... <items> ...<list values="x;y;k"/>
					itemsetStr = getSpecifiedInfo( xmlMsg,"//context/items/list","values") ;
					
					if (itemsetStr.length()>0){
					
						itemSet = itemsetStr.split(";");
						context.setItemSet(itemSet);
					}else{
						context = null;
					}
					
				}
				if (dataType == ContextInfra._DTYP_FVECTOR){
					// item set and values set
					// <context ...<pragma ... <items> ...<list values="x;y;k"/>
					itemsetStr = getSpecifiedInfo( xmlMsg,"//context/items/list","values") ;
					
					if (itemsetStr.length()>0){
					
						itemSet = itemsetStr.split(";");
						context.setItemSet(itemSet);
						context.setFeatureSet(itemSet);
						
						dataitemStr = getSpecifiedInfo( xmlMsg,"//context/values/list","values") ;
						datavaluesStr = dataitemStr.split(";") ;
						featureValues = strgutil.changeArrayType( datavaluesStr, -1.0, false ) ;
						context.setFeatureValues(featureValues) ;
						
					}else{
						context = null;
					}
				}
				if (dataType == ContextInfra._DTYP_FULLTEXT){
					// large text between <fulltext> .... </fulltext>
					
				}
				if (dataType == ContextInfra._DTYP_BINIMG){
					// encoded binary data between <bindata> .... </bindata>
					
				}
				
			} // context info
			
			if (stylev == ContextInfra._CSTYL_PLAIN){
				
			}
			if (stylev == ContextInfra._CSTYL_COMPLETE){  
				
				
			}
			
			
		    // if (str.length()>0){  iid = getLong(str,-1);
		    
		      
		}catch(Exception e){
			
		}
		
		
		
		return context;
	}			

}

